package com.jueming.cashbook.business.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.util.CollectionUtils;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 数据源配置（主MYSQL）
 * </p>
 *
 */
@Configuration
@MapperScan(
        basePackages = {"com.jueming.cashbook.business.mapper"},
        sqlSessionFactoryRef = "primarySqlSessionFactory"
)
public class PrimaryDataBaseConfig {
    @Primary
    @Bean(
            name = {"primaryDataSource"}
    )
    @ConfigurationProperties(prefix = "spring.datasource.druid.primary")
    public DataSource primaryDataSource() {
        return new DruidDataSource();
    }

    @Primary
    @Bean(
            name = {"primaryTransactionManager"}
    )
    public DataSourceTransactionManager primaryTransactionManager() {
        return new DataSourceTransactionManager(this.primaryDataSource());
    }

    @Primary
    @Bean(
            name = {"primarySqlSessionFactory"}
    )
    public SqlSessionFactory primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource primaryDataSource) throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(primaryDataSource);
        sqlSessionFactory.setMapperLocations(resolveMapperLocations());
        sqlSessionFactory.setTypeAliasesPackage("com.jueming.cashbook.entity");

        Resource resource = new ClassPathResource("mybatis/mybatis-config.xml");
        sqlSessionFactory.setConfigLocation(resource);

//        MybatisConfiguration configuration = new MybatisConfiguration();
//        configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
//        configuration.setJdbcTypeForNull(JdbcType.NULL);
//        configuration.setObjectWrapperFactory(new MybatisMapWrapperFactory());
//        sqlSessionFactory.setTypeAliasesPackage("com.tl.erp.buss.entity");
//        Resource resource = new DefaultResourceLoader().getResource("classpath:mybatis/dsno1/mybatis-config.xml");
//        sqlSessionFactory.setConfigLocation(resource);

        // sqlSessionFactory.setConfiguration(configuration);

        return sqlSessionFactory.getObject();
    }
    public Resource[] resolveMapperLocations() {
        ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
        List<String> mapperLocations = new ArrayList<>();
        mapperLocations.add("classpath:mybatis/*.xml");
        List<Resource> resources = new ArrayList();
        if (!CollectionUtils.isEmpty(mapperLocations)) {
            for (String mapperLocation : mapperLocations) {
                try {
                    Resource[] mappers = resourceResolver.getResources(mapperLocation);
                    for(int j=0;j<mappers.length;j++){
                        if(mappers[j].getFilename().indexOf("mybatis-config.xml")==-1){
                            resources.add(mappers[j]);
                        }
                    }
                } catch (IOException e) {
//                    syso
                }
            }
        }

        return resources.toArray(new Resource[resources.size()]);
    }
}
